<script setup lang="ts">
import { computed, inject, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue';
import { PARENT_TABS, tabpageProps } from './tabcontainSrc';

const props = defineProps(tabpageProps);
defineOptions({
  name: 'CTabpage'
});
const tabs: any = inject(PARENT_TABS);

const myActive = computed(() => {
  const t = tabs.value.find((tab) => tab.title === props.title && tab.icon === props.icon);
  return (t && t.active) || false;
});
const hasRendered = ref(false);
const tabPageRef = ref(null);
const tabpanelClass = computed(() => {
  return {
    'tab-pane': true,
    active: myActive.value
  };
});
const isShow = computed(() => {
  return myActive.value && props.show;
});
const isRenderNow = computed(() => {
  if (hasRendered.value) {
    return isShow.value || props.isKeepAlive;
  }
  return !props.lazyRender;
});

onMounted(() => {
  const defaultActive = tabs.value.length === 0;
  tabs.value.push({
    title: props.title,
    icon: props.icon,
    status: props.status,
    show: props.show,
    active: defaultActive
  });
});
onBeforeUnmount(() => {
  const index = tabs.value.findIndex((tab) => tab.title === props.title && tab.icon === props.icon);
  if (index >= 0) {
    tabs.value.splice(index, 1);
  }
});
</script>

<template>
  <transition name="fade" mode="out-in">
    <div v-if="isRenderNow" role="tabpanel" :class="tabpanelClass" :style="{ display: isShow ? 'block' : 'none' }">
      <slot ref="tabPageRef"></slot>
    </div>
  </transition>
</template>

<style lang="less"></style>
